{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using TensorFlow backend.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'2.0.0'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import keras\n",
    "keras.__version__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import os, shutil\n",
    "original_dir= #set working directory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "base_dir = # The directory where we will store our smaller dataset\n",
    "os.mkdir(base_dir)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Directories for our training and validation splits\n",
    "train_dir = os.path.join(base_dir, 'train')\n",
    "os.mkdir(train_dir)\n",
    "validation_dir = os.path.join(base_dir, 'validation')\n",
    "os.mkdir(validation_dir)\n",
    "\n",
    "\n",
    "#Create:\n",
    "# A directory with our training pictures of cut marks on defleshed bones\n",
    "train_nm_dir = os.path.join(train_dir, 'TM')\n",
    "os.mkdir(train_nm_dir)\n",
    "\n",
    "# Directory with our training pictures of cut marks on fleshed bones\n",
    "train_wm_dir = os.path.join(train_dir, 'WM')\n",
    "os.mkdir(train_wm_dir)\n",
    "\n",
    "# Directory with our validation pictures of cut marks on defleshed bones\n",
    "validation_nm_dir = os.path.join(validation_dir, 'TM')\n",
    "os.mkdir(validation_nm_dir)\n",
    "\n",
    "# Directory with our validation pictures of cut marks on fleshed bones\n",
    "validation_wm_dir = os.path.join(validation_dir, 'WM')\n",
    "os.mkdir(validation_wm_dir)\n",
    "\n",
    "# Directory with our validation pictures of cut marks on defleshed bones\n",
    "test_nm_dir = os.path.join(test_dir, 'TM')\n",
    "os.mkdir(test_nm_dir)\n",
    "\n",
    "# Directory with our validation pictures of cut marks on fleshed bones\n",
    "test_wm_dir = os.path.join(test_dir, 'WM')\n",
    "os.mkdir(test_wm_dir)\n",
    "\n",
    "# Copy first CM images to train_nm_dir\n",
    "fnames = ['TM.{}.bmp'.format(i) for i in range(40)]\n",
    "for fname in fnames:\n",
    "    src = os.path.join(original_dir, fname)\n",
    "    dst = os.path.join(train_nm_dir, fname)\n",
    "    shutil.copyfile(src, dst)\n",
    "\n",
    "# Copy next CM images to validation_nm_dir\n",
    "fnames = ['TM.{}.bmp'.format(i) for i in range(40, 60)]\n",
    "for fname in fnames:\n",
    "    src = os.path.join(original_dir, fname)\n",
    "    dst = os.path.join(validation_nm_dir, fname)\n",
    "    shutil.copyfile(src, dst)\n",
    "    \n",
    "    \n",
    "# Copy first CM images to train_wm_dir\n",
    "fnames = ['WM.{}.bmp'.format(i) for i in range(90)]\n",
    "for fname in fnames:\n",
    "    src = os.path.join(original_dir, fname)\n",
    "    dst = os.path.join(train_wm_dir, fname)\n",
    "    shutil.copyfile(src, dst)\n",
    "    \n",
    "# Copy next 10 CM images to validation_wm_dir\n",
    "fnames = ['WM.{}.bmp'.format(i) for i in range(90, 130)]\n",
    "for fname in fnames:\n",
    "    src = os.path.join(original_dir, fname)\n",
    "    dst = os.path.join(validation_wm_dir, fname)\n",
    "    shutil.copyfile(src, dst)\n",
    "    \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras import layers\n",
    "from keras import models\n",
    "\n",
    "#height, width, channels\n",
    "model = models.Sequential()\n",
    "model.add(layers.Conv2D(32, (3, 3), activation='relu',\n",
    "                        input_shape=(80, 400, 3)))#cambiar 1 a 3 si es color\n",
    "model.add(layers.MaxPooling2D((2, 2)))\n",
    "model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n",
    "model.add(layers.MaxPooling2D((2, 2)))\n",
    "model.add(layers.Conv2D(128, (3, 3), activation='relu'))\n",
    "model.add(layers.MaxPooling2D((2, 2)))\n",
    "model.add(layers.Conv2D(128, (3, 3), activation='relu'))\n",
    "model.add(layers.MaxPooling2D((2, 2)))\n",
    "model.add(layers.Flatten())\n",
    "model.add(layers.Dense(512, activation='relu'))\n",
    "model.add(layers.Dense(1, activation='sigmoid'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from keras import optimizers\n",
    "\n",
    "model.compile(loss='binary_crossentropy',\n",
    "              optimizer=optimizers.RMSprop(lr=1e-4),\n",
    "              metrics=['acc'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras.preprocessing.image import ImageDataGenerator\n",
    "\n",
    "# All images will be rescaled by 1./255\n",
    "train_datagen = ImageDataGenerator(rescale=1./255)\n",
    "test_datagen = ImageDataGenerator(rescale=1./255)\n",
    "\n",
    "train_generator = train_datagen.flow_from_directory(\n",
    "        # This is the target directory\n",
    "        train_dir,\n",
    "        # All images will be resized to 40x160\n",
    "        target_size=(80, 400),\n",
    "        batch_size=32,\n",
    "        # Since we use binary_crossentropy loss, we need binary labels\n",
    "        class_mode='binary')\n",
    "\n",
    "validation_generator = test_datagen.flow_from_directory(\n",
    "        validation_dir,\n",
    "        target_size=(80, 400),\n",
    "        batch_size=10,\n",
    "        class_mode='binary')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "history = model.fit_generator(\n",
    "      train_generator,\n",
    "      steps_per_epoch=5,\n",
    "      epochs=100,\n",
    "      validation_data=validation_generator,\n",
    "      validation_steps=6)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "acc = history.history['acc']\n",
    "val_acc = history.history['val_acc']\n",
    "loss = history.history['loss']\n",
    "val_loss = history.history['val_loss']\n",
    "\n",
    "epochs = range(len(acc))\n",
    "\n",
    "plt.plot(epochs, acc, 'bo', label='Training acc')\n",
    "plt.plot(epochs, val_acc, 'b', label='Validation acc')\n",
    "plt.title('Training and validation accuracy')\n",
    "plt.legend()\n",
    "\n",
    "plt.figure()\n",
    "\n",
    "plt.plot(epochs, loss, 'bo', label='Training loss')\n",
    "plt.plot(epochs, val_loss, 'b', label='Validation loss')\n",
    "plt.title('Training and validation loss')\n",
    "plt.legend()\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#This is the model to use with image augmentation\n",
    "\n",
    "from keras.preprocessing.image import ImageDataGenerator\n",
    "\n",
    "train_datagen = ImageDataGenerator(\n",
    "      rescale=1./255,\n",
    "      rotation_range=40,\n",
    "      width_shift_range=0.2,\n",
    "      height_shift_range=0.2,\n",
    "      shear_range=0.2,\n",
    "      zoom_range=0.2,\n",
    "      horizontal_flip=True,\n",
    "      fill_mode='nearest')\n",
    "\n",
    "# Note that the validation data should not be augmented!\n",
    "test_datagen = ImageDataGenerator(rescale=1./255)\n",
    "\n",
    "train_generator = train_datagen.flow_from_directory(\n",
    "        # This is the target directory\n",
    "        train_dir,\n",
    "        # All images will be resized to 150x150\n",
    "        target_size=(80, 400),\n",
    "        batch_size=32,\n",
    "        # Since we use binary_crossentropy loss, we need binary labels\n",
    "        class_mode='binary')\n",
    "\n",
    "validation_generator = test_datagen.flow_from_directory(\n",
    "        validation_dir,\n",
    "        target_size=(80, 400),\n",
    "        batch_size=10,\n",
    "        class_mode='binary')\n",
    "\n",
    "model.compile(loss='binary_crossentropy',\n",
    "              optimizer=optimizers.RMSprop(lr=2e-5),\n",
    "              metrics=['acc'])\n",
    "\n",
    "history = model.fit_generator(\n",
    "      train_generator,\n",
    "      steps_per_epoch=5,\n",
    "      epochs=100,\n",
    "      validation_data=validation_generator,\n",
    "      validation_steps=6,\n",
    "      verbose=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "acc = history.history['acc']\n",
    "val_acc = history.history['val_acc']\n",
    "loss = history.history['loss']\n",
    "val_loss = history.history['val_loss']\n",
    "\n",
    "epochs = range(len(acc))\n",
    "\n",
    "plt.plot(epochs, acc, 'bo', label='Training acc')\n",
    "plt.plot(epochs, val_acc, 'b', label='Validation acc')\n",
    "plt.title('Training and validation accuracy')\n",
    "plt.legend()\n",
    "\n",
    "plt.figure()\n",
    "\n",
    "plt.plot(epochs, loss, 'bo', label='Training loss')\n",
    "plt.plot(epochs, val_loss, 'b', label='Validation loss')\n",
    "plt.title('Training and validation loss')\n",
    "plt.legend()\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
